package com.hwd.gmall.user.filter;


import com.hwd.gmall.common.constant.CartConst;
import com.hwd.gmall.common.util.MyThreadLocal;
import com.hwd.gmall.user.util.TokenUtil;
import org.springframework.core.annotation.Order;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/**
 * 自定义购物车微服务的过滤器
 *
 * @author 黄伟东/Victor
 * @date 2022/5/6 16:08
 */
@WebFilter(filterName = "userFilter", urlPatterns = {"/*"})
@Order(1)
public class UserFilter extends GenericFilterBean {

    /**
     * 自定义过滤的逻辑
     *
     * @param servletRequest  请求对象
     * @param servletResponse 响应对象
     * @param filterChain     过滤链
     */
    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain filterChain) throws ServletException, IOException {
        // 获取请求对象
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        // 在请求对象中获取用户名
        String token = request.getHeader(CartConst.AUTHORIZATION).replace(CartConst.AUTHORIZATION_PREFIX, "");
        Map<String, String> tokenMap = TokenUtil.decodeToken(token);

        if (tokenMap != null && !tokenMap.isEmpty()) {
            // 获取用户名
            String username = tokenMap.get(CartConst.USERNAME);
            // 往本地线程对象中保存用户名
            MyThreadLocal.set(username);
        }

        //放行
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
